package com.lxg.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author 陆小根
 * date: 2022/04/24
 * Description:
 * 自定义前后端分离Filter
 */

public class LoginFilter extends UsernamePasswordAuthenticationFilter {

  @Override
  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

    // 1.判断是否是 post 方式请求
    if (!request.getMethod().equals("POST")) {
      throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    }
    // 2.判断是否是 json 格式请求类型
    if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
      // 3.从 json 数据中获取用户输入用户名和密码进行认证 {"uname":"xxx", "password":"xxx"}
      try {
        // 序列化我们的json数据
        Map<String, String> userInfo = new ObjectMapper().readValue(request.getInputStream(), Map.class);
        String username = userInfo.get(getUsernameParameter());
        String password = userInfo.get(getPasswordParameter());
        System.out.println("用户名: " + username + " 密码:" + password);

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return super.attemptAuthentication(request, response);
  }
}
